import requests
import configparser
import logging
import os
import sys
from config import ENV, CONFIG_PATH, setup_logger

def log_info(msg):
    logging.info(msg)

def log_error(msg):
    logging.error(msg)

def get_config_path():
    return CONFIG_PATH

def getCurrentLoginInfo():
    """
    判断token是否有效，返回True为有效，False为失效。
    """
    config_path = get_config_path()
    config = configparser.ConfigParser()
    config.read(config_path, encoding='utf-8')
    # 读取token
    token = config.get('token', 'access_token', fallback=None)
    # 读取headers
    headers = dict(config.items('getCurrentLoginInfo_headers'))
    headers['authorization'] = f'Bearer {token}'
    headers['referer'] = f'https://xhgz-test.xiaojiaoyu100.com/courseware/content/teaching?token={token}'
    # 读取cookies
    cookies = dict(config.items('getCurrentLoginInfo_cookies'))
    cookies['token'] = token
    # refresh_token可选
    if not cookies.get('refresh_token'):
        cookies.pop('refresh_token', None)
    url = config.get('urls', 'getCurrentLoginInfo_url')
    try:
        log_info(f"校验token有效性，请求: {url}")
        resp = requests.post(url, cookies=cookies, headers=headers, json={})
        data = resp.json()
        log_info(f"getCurrentLoginInfo接口返回: {data}")
        if data.get('fail') is True:
            log_info("token失效，需重新登录。")
            return False
        else:
            log_info("token有效。")
            return True
    except Exception as e:
        log_error(f"校验token异常: {e}")
        return False

def login_and_save_token():
    """
    登录接口：请求 access_token 并写入 config.ini。
    """
    config_path = get_config_path()
    config = configparser.ConfigParser()
    config.optionxform = str  # 保持区块和键的大小写
    config.read(config_path, encoding='utf-8')
    old_token = config.get('token', 'access_token', fallback=None)
    try:
        headers = dict(config.items('login_headers'))
        log_info(f"读取登录headers成功: {headers}")
    except Exception as e:
        log_error(f"读取login_headers失败: {e}")
        return
    try:
        params = dict(config.items('login_params'))
        log_info(f"读取登录参数成功: {params}")
    except Exception as e:
        log_error(f"读取login_params失败: {e}")
        return
    url = config.get('urls', 'login_url')
    try:
        log_info(f"发送登录请求到: {url} ...")
        response = requests.post(url, params=params, headers=headers)
        log_info(f"登录接口响应状态: {response.status_code}")
        response.raise_for_status()
        log_info(f"登录接口原始响应内容: {response.text}")
        try:
            data = response.json()
        except Exception as e:
            log_error(f"解析JSON失败，原始内容: {response.text}")
            raise
        log_info(f"登录接口返回: {data}")
        access_token = data.get('access_token')
        if access_token:
            # 重新读取所有配置，防止写入时丢失其他区块
            config.read(config_path, encoding='utf-8')
            if 'token' not in config:
                config['token'] = {}
            config['token']['access_token'] = access_token
            with open(config_path, 'w', encoding='utf-8') as configfile:
                config.write(configfile)
            if old_token == access_token:
                log_info(f"新旧token一致，token未变: {access_token}")
            else:
                log_info(f"新旧token不一致，token已变！新token: {access_token}，旧token: {old_token}")
            log_info(f"登录成功，access_token 已保存到 config.ini: {access_token}")
        else:
            log_error(f"登录失败，未获取到 access_token，返回内容: {data}")
    except Exception as e:
        log_error(f"请求或保存 token 失败: {e}")

if __name__ == "__main__":
    setup_logger()
    login_and_save_token()
